package com.hemaapp.yjnh.activity;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.ClientDetails;

/**
 * 卖家地图页面
 */
public class SellerMapActivity extends BaseActivity implements LocationSource,
		AMapLocationListener {
	private MapView mapView;
	private ImageButton back_btn;
	private ImageButton loc_btn;
	private TextView seller_name_txt;
	private TextView seller_addr_txt;
	private Button route_btn;
	private ImageView markerView;

	private AMap aMap;
	private AMapLocationClient mlocationClient;
	private OnLocationChangedListener mListener;
	private AMapLocationClientOption mLocationOption;
	
	private ClientDetails merchantExra;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_sellermap);
		super.onCreate(savedInstanceState);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		initMap();
	}

	private void initMap() {
		if (aMap == null) {
			aMap = mapView.getMap();
			aMap.setLocationSource(this);// 设置定位监听
//			aMap.getUiSettings().setCompassEnabled(true);//指南针
//			aMap.getUiSettings().setScaleControlsEnabled(true);
			// aMap.getUiSettings().setMyLocationButtonEnabled(true);//
			// 设置默认定位按钮是否显示
			// aMap.setMyLocationEnabled(false);//
			// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
			try {
				double lat = Double.parseDouble(merchantExra.getLat());
				double lng = Double.parseDouble(merchantExra.getLng());
				final LatLng latLng = new LatLng(lat, lng);
				CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,
						17);
				aMap.moveCamera(update);
				markerView.setDrawingCacheEnabled(true);
				Bitmap bitmap = markerView.getDrawingCache();
				BitmapDescriptor descriptor = BitmapDescriptorFactory
						.fromResource(R.drawable.bg_type_marker);
				aMap.addMarker(new MarkerOptions().icon(descriptor).
						position(latLng).anchor(0, 0));
				markerView.setDrawingCacheEnabled(false);
			} catch (Exception e) {
				XtomToastUtil.showShortToast(mContext, "获取商家详细地址失败");
			}
		}
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {

	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
	}

	@Override
	protected void findView() {
		back_btn = (ImageButton) findViewById(R.id.back_btn);
		loc_btn = (ImageButton) findViewById(R.id.loc_btn);
		seller_name_txt = (TextView) findViewById(R.id.seller_name);
		seller_addr_txt = (TextView) findViewById(R.id.seller_addr);
		route_btn = (Button) findViewById(R.id.route_btn);

		mapView = (MapView) findViewById(R.id.bmapView);
		markerView = (ImageView) findViewById(R.id.markerview);
	}

	@Override
	protected void getExras() {
		merchantExra = (ClientDetails) mIntent.getSerializableExtra("merchant");
	}

	@Override
	protected void setListener() {
		back_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		loc_btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// location_back();
				log_i("定位");
				aMap.setMyLocationEnabled(false);
				aMap.setMyLocationEnabled(true);
			}
		});

		route_btn.setOnClickListener(new RouteListener());

		seller_name_txt.setText(merchantExra.getNickname());
		seller_addr_txt.setText(merchantExra.getAddress());
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mlocationClient == null) {
			mlocationClient = new AMapLocationClient(this);
			mLocationOption = new AMapLocationClientOption();
			//设置定位监听
			mlocationClient.setLocationListener(this);
			//设置为高精度定位模式
			mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
			//设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			mlocationClient.startLocation();
		}
	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;
	}

	@Override
	public void onLocationChanged(AMapLocation location) {
		if (mListener != null && location != null) {
			mListener.onLocationChanged(location);// 显示系统小蓝点
			float bearing = aMap.getCameraPosition().bearing;
			aMap.setMyLocationRotateAngle(bearing);// 设置小蓝点旋转角度

			Double lat = location.getLatitude();
			Double lng = location.getLongitude();
			BaseApplication application = BaseApplication.getInstance();
			XtomSharedPreferencesUtil.save(application, "lat", lat.toString());
			XtomSharedPreferencesUtil.save(application, "lng", lng.toString());
			saveCityId(location.getCityCode());
		}
		deactivate();
	}

	private class RouteListener implements OnClickListener {
		@Override
		public void onClick(View v) {

			try {
				double lat = Double.parseDouble(merchantExra.getLat());
				double lng = Double.parseDouble(merchantExra.getLng());
				LatLonPoint toPoint = new LatLonPoint(lat, lng);

				String mLat = XtomSharedPreferencesUtil.get(mContext, "lat");
				String mLng = XtomSharedPreferencesUtil.get(mContext, "lng");
				double dLat = Double.parseDouble(mLat);
				double dLng = Double.parseDouble(mLng);
				LatLonPoint fromPoint = new LatLonPoint(dLat, dLng);

				Intent it = new Intent(mContext, RouteSearchActivity.class);
				it.putExtra("toName", merchantExra.getNickname());
				it.putExtra("toPoint", toPoint);
				it.putExtra("fromPoint", fromPoint);
				startActivity(it);
			} catch (Exception e) {
				showTextDialog("2者位置有问题,不能查看路线");
				return;
			}

		}
	}
}
